package com.jkgl.util;

import com.alibaba.fastjson2.JSON;
import com.jkgl.context.RedisStreamContext;
import com.jkgl.entity.MesPersistence;
import com.jkgl.entity.UserInfoDayEntity;
import com.jkgl.entity.UserInfoSelfEntity;
import com.jkgl.mq.MessageProducer;
import com.jkgl.result.Report;
import com.jkgl.service.MesPersistenceService;
import com.jkgl.stream.MailSenderObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.UUID;

@Slf4j
@RequiredArgsConstructor
@Component
public class SendStreamUtil {
    private final MessageProducer producer;
    private final MesPersistenceService persistenceService;


    /**
     * 发送MQ到Mail服务  村表 发邮件
     *
     * @param report
     */
    public void transferMail(Report report) {
        if (report == null) {
            log.error("发送MQ失败 report:null");
            sendError(null, "report 为null");
            return;
        }
        String messageKey = UUID.randomUUID().toString();
        String reportJson = JSON.toJSONString(report);
//        应该不会存在空指针--user有才会遍历 并set
        RecordId result = producer.sendMessage(
                RedisStreamContext.REPORT_STREAM_TOPIC,
                messageKey,reportJson
                );
        log.info("发送报告-{}---结果{}", messageKey, result);
//          TODO  做表存
        if (result == null) {
            sendError(null, "健康报告RecordId 为 null 发送失败");
        }
        MesPersistence build = MesPersistence.builder().createTime(LocalDateTime.now())
                .messageId(result == null ? messageKey : result.toString())
                .isSuccess(1)
                .messageType(2)
                .context(reportJson)
                .isSend(result == null ? 1 : 2)
                .userId(report.getUserId())
                .build();
        persistenceService.save(build);
    }


    /**
     * 发生错误 存表 并且发邮件
     *
     * @param error
     * @param mess
     */
    public void sendError(Object error, String mess) {
        log.info("发生错误信息:{}\n{}", error, mess);
        String messageKey = UUID.randomUUID().toString();

        String context = JSON.toJSONString(
                MailSenderObject.builder()
                        .obj(error)
                        .mess(mess)
                );
        RecordId result = producer.sendMessage(RedisStreamContext.ERROR_STREAM_TOPIC,
                messageKey,
                context);
        if (result == null) {
            sendError(null, "异常短信RecordId 为 null 发送失败");
        }
        MesPersistence build = MesPersistence.builder().createTime(LocalDateTime.now())
                .messageId(result == null ? messageKey : result.toString())
                .isSuccess(1)
                .messageType(2)
                .context(context)
                .isSend(result == null ? 1 : 2)
                .build();
        persistenceService.save(build);
    }

    /**
     * 运动提醒MQ
     *
     * @param type 1早/2晚
     * @param day  日数据
     * @param self 自身数据
     * @param mail  邮箱地址
     */
    public void sendSportNotice(Integer type, UserInfoDayEntity day, UserInfoSelfEntity self,String mail) {
        log.info("发送运动提醒:{}\n{}", type == 1 ? "早" : "晚", self.getUserId());
        String messageKey = UUID.randomUUID().toString();
        String context = null;
        if(day == null){
            context = "今日运动信息未登记！！";
        }else if (type == 1) {
//            TODO 记得做json 改模板
            //早--运动提醒
            context = "运动提醒：" +
                    "\n 今日目标:" + self.getTargetStep() +
                    "\n 记得按时打卡";

        } else if (type == 2) {
            String s =day.getStepNumber() > self.getTargetStep() ? "今日运动已经达标！再接再厉！":"\n 今日任务未达标";
            context = "运动提醒: " +
                    "\n 今日步数:" + day.getStepNumber() +"/" + self.getTargetStep() +
                    "\n 今日数据: "+ "~~~\n" +s
                   ;
        }
        RecordId result = producer.sendMessage(RedisStreamContext.NOTICE_STREAM_TOPIC,
                messageKey,
                JSON.toJSONString(MailSenderObject.builder()
                        .obj(context)
                        .mess(mail).build()));
        if (result == null) {
            sendError(null, type == 1 ? "早" : "晚" + "---报告" + "RecordId 为 null 发送失败");
        }
        MesPersistence build = MesPersistence.builder().createTime(LocalDateTime.now())
                .messageId(result == null ? messageKey : result.toString())
                .isSuccess(1)
                .messageType(3)
                .context(context)
                .isSend(2)
                .userId(Long.valueOf(self.getUserId()))
                .build();
        persistenceService.save(build);
    }
}
